package com.gitee.blogcase.dealyqueuecase.controller;

import com.gitee.blogcase.dealyqueuecase.rabbitmq.deadletter.config.DeadLetterQueueConfig;
import com.gitee.blogcase.dealyqueuecase.rabbitmq.delayed.config.DelayedQueueConfig;
import com.gitee.blogcase.dealyqueuecase.utils.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;

/**
 * RabbitMQ 死信队列实现RabbitMQ
 * @author wuwentoa
 */
@Slf4j
@RestController
@RequestMapping("rabbit/dealyed/queue")
@AllArgsConstructor
public class RabbitDelayedQueueProducer {
    private RabbitTemplate rabbitTemplate;
    /**
     * 投递订单到延迟消息队列中
     * http://localhost:8022/rabbit/dealyed/queue/sendMessage?orderId=100000001
     * http://localhost:8022/rabbit/dealyed/queue/sendMessage?orderId=100000002
     * http://localhost:8022/rabbit/dealyed/queue/sendMessage?orderId=100000003
     * http://localhost:8022/rabbit/dealyed/queue/sendMessage?orderId=100000004
     * http://localhost:8022/rabbit/dealyed/queue/sendMessage?orderId=100000005
     * @param orderId 订单ID
     */
    @GetMapping("/sendMessage")
    public String sendMessage(@RequestParam(value = "orderId") String orderId){
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE, DelayedQueueConfig.DELAYED_ROUTING_KEY, orderId, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置消息超时时间
                message.getMessageProperties().setHeader("x-delay", DelayedQueueConfig.ORDER_OUTIME);
                return message;
            }
        });
        log.info("当前时间:{} 订单号:{}", DateUtil.getCuurentDateStr(),orderId);
        return "OK";
    }
}
